<template>
  <div class="role-management-container">
    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="角色编码">
          <el-input
            v-model="searchForm.code"
            placeholder="请输入角色编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="角色状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="全部" value="" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline icon="ep:search" class="mr-1" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-bar">
        <div class="action-left">
          <el-button type="primary" @click="handleAdd">
            <IconifyIconOffline icon="ep:plus" class="mr-1" />
            新增角色
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedRoles.length === 0"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline icon="ep:delete" class="mr-1" />
            批量删除
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline icon="ep:download" class="mr-1" />
            导出角色
          </el-button>
        </div>

        <div class="action-right">
          <el-button circle @click="handleRefresh">
            <IconifyIconOffline icon="ep:refresh" />
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 角色列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="roleList"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column prop="name" label="角色名称" width="150" />

        <el-table-column prop="code" label="角色编码" width="150" />

        <el-table-column
          prop="description"
          label="角色描述"
          min-width="200"
          show-overflow-tooltip
        />

        <el-table-column
          prop="userCount"
          label="用户数量"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-link type="primary" @click="handleViewUsers(row)">
              {{ row.userCount }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序" width="80" align="center" />

        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handlePermission(row)"
            >
              权限
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              :disabled="row.isSystem"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog v-model="formVisible" :title="formTitle" width="600px">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色编码" prop="code">
          <el-input
            v-model="formData.code"
            placeholder="请输入角色编码"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 权限配置弹窗 -->
    <el-dialog v-model="permissionVisible" title="权限配置" width="800px">
      <div v-if="currentRole" class="permission-content">
        <div class="permission-header">
          <span>为角色 "{{ currentRole.name }}" 分配权限</span>
          <div class="permission-actions">
            <el-button size="small" @click="handleExpandAll">
              <IconifyIconOffline icon="ep:plus" class="mr-1" />
              展开全部
            </el-button>
            <el-button size="small" @click="handleCollapseAll">
              <IconifyIconOffline icon="ep:minus" class="mr-1" />
              收起全部
            </el-button>
            <el-button size="small" @click="handleSelectAll">
              <IconifyIconOffline icon="ep:check" class="mr-1" />
              全选
            </el-button>
            <el-button size="small" @click="handleDeselectAll">
              <IconifyIconOffline icon="ep:close" class="mr-1" />
              取消全选
            </el-button>
          </div>
        </div>

        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          class="permission-tree"
        />
      </div>

      <template #footer>
        <el-button @click="permissionVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitPermission"
          >保存权限</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";

// 搜索表单
const searchForm = reactive({
  name: "",
  code: "",
  status: ""
});

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
});

// 状态
const loading = ref(false);
const submitting = ref(false);
const selectedRoles = ref([]);
const formVisible = ref(false);
const permissionVisible = ref(false);
const isEdit = ref(false);
const currentRole = ref(null);
const formRef = ref();
const permissionTreeRef = ref();

// 表单数据
const formData = reactive({
  id: null,
  name: "",
  code: "",
  description: "",
  sort: 0,
  status: 1,
  remark: ""
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  code: [
    { required: true, message: "请输入角色编码", trigger: "blur" },
    {
      pattern: /^[A-Z_]+$/,
      message: "角色编码只能包含大写字母和下划线",
      trigger: "blur"
    }
  ],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }]
};

// 权限树配置
const treeProps = {
  children: "children",
  label: "name"
};

const checkedPermissions = ref([]);

// 角色列表数据
const roleList = ref([
  {
    id: 1,
    name: "超级管理员",
    code: "SUPER_ADMIN",
    description: "系统超级管理员，拥有所有权限",
    userCount: 1,
    status: 1,
    sort: 1,
    isSystem: true,
    createTime: "2024-01-01 00:00:00"
  },
  {
    id: 2,
    name: "管理员",
    code: "ADMIN",
    description: "系统管理员，拥有大部分管理权限",
    userCount: 5,
    status: 1,
    sort: 2,
    isSystem: false,
    createTime: "2024-01-15 10:30:00"
  },
  {
    id: 3,
    name: "普通用户",
    code: "USER",
    description: "普通用户，拥有基本功能权限",
    userCount: 100,
    status: 1,
    sort: 3,
    isSystem: false,
    createTime: "2024-01-15 14:20:00"
  }
]);

// 权限树数据
const permissionTree = ref([
  {
    id: 1,
    name: "用户管理",
    children: [
      { id: 11, name: "用户列表" },
      { id: 12, name: "用户新增" },
      { id: 13, name: "用户编辑" },
      { id: 14, name: "用户删除" }
    ]
  },
  {
    id: 2,
    name: "角色管理",
    children: [
      { id: 21, name: "角色列表" },
      { id: 22, name: "角色新增" },
      { id: 23, name: "角色编辑" },
      { id: 24, name: "角色删除" },
      { id: 25, name: "权限分配" }
    ]
  },
  {
    id: 3,
    name: "俱乐部管理",
    children: [
      { id: 31, name: "俱乐部列表" },
      { id: 32, name: "俱乐部审核" },
      { id: 33, name: "成员管理" }
    ]
  },
  {
    id: 4,
    name: "活动管理",
    children: [
      { id: 41, name: "活动列表" },
      { id: 42, name: "活动创建" },
      { id: 43, name: "活动编辑" },
      { id: 44, name: "活动删除" }
    ]
  }
]);

// 计算属性
const formTitle = computed(() => {
  return isEdit.value ? "编辑角色" : "新增角色";
});

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm");
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadRoleList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    code: "",
    status: ""
  });
  handleSearch();
};

// 新增角色
const handleAdd = () => {
  isEdit.value = false;
  Object.assign(formData, {
    id: null,
    name: "",
    code: "",
    description: "",
    sort: 0,
    status: 1,
    remark: ""
  });
  formVisible.value = true;
};

// 编辑角色
const handleEdit = (role: any) => {
  isEdit.value = true;
  Object.assign(formData, { ...role });
  formVisible.value = true;
};

// 删除角色
const handleDelete = async (role: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    ElMessage.success("删除成功");
    loadRoleList();
  } catch {
    // 用户取消
  }
};

// 批量删除
const handleBatchDelete = () => {
  ElMessage.info("批量删除功能开发中");
};

// 导出角色
const handleExport = () => {
  ElMessage.success("导出成功");
};

// 刷新
const handleRefresh = () => {
  loadRoleList();
};

// 状态变化
const handleStatusChange = (role: any) => {
  ElMessage.success(`角色状态已${role.status ? "启用" : "禁用"}`);
};

// 权限配置
const handlePermission = (role: any) => {
  currentRole.value = role;
  // 模拟已分配的权限
  checkedPermissions.value = [11, 12, 21, 22, 31, 41];
  permissionVisible.value = true;
};

// 查看用户
const handleViewUsers = (role: any) => {
  ElMessage.info(`查看角色 "${role.name}" 的用户列表`);
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRoles.value = selection;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));

    ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
    formVisible.value = false;
    loadRoleList();
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitting.value = false;
  }
};

// 权限树操作
const handleExpandAll = () => {
  const tree = permissionTreeRef.value;
  if (tree) {
    permissionTree.value.forEach(node => {
      tree.setExpanded(node.id, true);
    });
  }
};

const handleCollapseAll = () => {
  const tree = permissionTreeRef.value;
  if (tree) {
    permissionTree.value.forEach(node => {
      tree.setExpanded(node.id, false);
    });
  }
};

const handleSelectAll = () => {
  const tree = permissionTreeRef.value;
  if (tree) {
    const allKeys: number[] = [];
    const collectKeys = (nodes: any[]) => {
      nodes.forEach(node => {
        allKeys.push(node.id);
        if (node.children) {
          collectKeys(node.children);
        }
      });
    };
    collectKeys(permissionTree.value);
    tree.setCheckedKeys(allKeys);
  }
};

const handleDeselectAll = () => {
  const tree = permissionTreeRef.value;
  if (tree) {
    tree.setCheckedKeys([]);
  }
};

// 提交权限
const handleSubmitPermission = () => {
  const tree = permissionTreeRef.value;
  if (tree) {
    const checkedKeys = tree.getCheckedKeys();
    console.log("选中的权限:", checkedKeys);
    ElMessage.success("权限保存成功");
    permissionVisible.value = false;
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  loadRoleList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadRoleList();
};

// 加载角色列表
const loadRoleList = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    pagination.total = 50;
  } catch (error) {
    ElMessage.error("加载角色列表失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadRoleList();
});
</script>

<style scoped lang="scss">
.role-management-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.search-form {
  .el-form-item {
    margin-bottom: 16px;
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .action-left {
    display: flex;
    gap: 8px;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.permission-content {
  .permission-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;

    .permission-actions {
      display: flex;
      gap: 8px;
    }
  }

  .permission-tree {
    max-height: 400px;
    overflow-y: auto;
  }
}

@media (max-width: 768px) {
  .role-management-container {
    padding: 10px;
  }

  .search-form {
    .el-form-item {
      width: 100%;
      margin-bottom: 12px;

      .el-input,
      .el-select {
        width: 100% !important;
      }
    }
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left {
      flex-wrap: wrap;
    }

    .action-right {
      align-self: flex-end;
    }
  }

  .permission-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .permission-actions {
      flex-wrap: wrap;
    }
  }
}
</style>
